package com.spx.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spx.usercenter.model.domain.User;
import com.spx.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private UserService userService;
    private List<Long> mainUserList = Arrays.asList(1L);

    @Scheduled(cron = "30 45 17 * * *")
    private void doCacheRecommendUser(){

        RLock lock = redissonClient.getLock("zsynpart:precache:doCache:lock");

        try {
            if (lock.tryLock(0, 30000L, TimeUnit.MILLISECONDS)){
                System.out.println("getLock: " + Thread.currentThread().getId());
                for (Long userId : mainUserList) {
                    ValueOperations valueOperations = redisTemplate.opsForValue();

                    QueryWrapper<User> wrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), wrapper);
                    String redisKey = String.format("zsynpart:user:recommend:%s", userId);
                    //写缓存
                    try {
                        valueOperations.set(redisKey,userPage, 300000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            //只能释放自己的锁
            if (lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }


    }
}
